const db=uniCloud.database();
module.exports = {
	_before: function () { // 通用预处理器

	},

	async add(params){
		params.price=Number(params.price).toFixed(2)*100;
		params.before_price=params.before_price ? Number(params.before_price).toFixed(2)*100:null;
		return await db.collection("mall-goods").add(params);
	},
	async getList(){
		let navData=await db.collection("mall-categories").get();
		let goodsData=await db.collection("mall-goods").get();
		navData.data.forEach(item=>{
			let proGroup=goodsData.data.filter(g=>{
				return g.category_id==item._id;
			});
			item.proGroup=proGroup;
		});
		
		let narr=navData.data.filter(item=>{
			return item.proGroup.length;
		})
		return {data:narr};
	},
	async remove(id){
		return await db.collection("mall-goods").doc(id).remove();
	},
	async getOne(id){
		let res=await db.collection("mall-goods").doc(id).get();
		res.data[0].price=res.data[0].price/100;
		res.data[0].before_price=res.data[0].before_price? res.data[0].before_price/100:null;
		return res;
	},
	
	async update(params) {
		let _params = {
			...params
		};
		delete _params._id;
		
		_params.price=Number(_params.price).toFixed(2)*100;
		_params.before_price=_params.before_price ? Number(_params.before_price).toFixed(2)*100:null;
		
		return await db.collection("mall-goods").doc(params._id).update(_params);
	}
}
